
// 策略基本信息接口数据类
export interface StrategyInfoResponse {
    data: {
        strategyList: Array<{
            strategyName: string;
            strategyID: number;
        }>;
        reportDate: string[];
    }
}

// 策略选股结果接口数据类
export interface StrategyStockResponse {
    data: {
        code: string;
        shortName: string;
        industryName: string;
        signal: number;
    }[];
}

// 策略基本信息接口请求
export const fetchStrategyInfo = async (): Promise<StrategyInfoResponse> => {
  try {
    const response = await fetch('http://localhost:8000/strategy_info/strategyInfos', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({}),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return data;
  }

  catch (error) {
    console.error('获取策略信息失败:', error);
    throw error;
  }
};

// 策略选股结果接口请求
export const fetchStrategyStocks = async (strategyType: number, reportDate: string): Promise<StrategyStockResponse> => {
    try {
        const response = await fetch('http://localhost:8000/strategy_info/strategyStocks', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                strategy_category: strategyType,
                report_date: reportDate,
            }),
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        return data;
        }
    catch (error) {
        console.error('获取策略选股结果失败:', error);
        throw error;
    }
};

// 基本面研究流式接口
const FundamentalAgentAPI = {
  streamAnalysis: (
    userInput: string,
    stockCode: string,
    reportDate: string,
    onMessage: (data: string) => void
  ): EventSource => {
    const params = new URLSearchParams({
      userInput,
      stockCode,
      reportDate,
    });

    const url = `http://localhost:8000/agents_sse/multiagents/fundamental?${params.toString()}`;

    // 创建 SSE
    const eventSource = new EventSource(url, { withCredentials: false });

    // 浏览器自动解析为json
    eventSource.onmessage = (event) => {
      try {
        const dataStr = event.data;

        // 兼容"[DONE]"表示结束
        if (dataStr === "[DONE]") {
          const endEvent = new Event("end");
          eventSource.dispatchEvent(endEvent);
          return;
        }

        const json = JSON.parse(dataStr);

        // 兼容 {"state": "done"} 则流结束
        if (json.state === "done") {
          const endEvent = new Event("end");
          eventSource.dispatchEvent(endEvent);
          return;
        }

        onMessage(dataStr);
      } catch (err) {
        console.error("❌ SSE JSON 解析失败:", err, "原始数据:", event.data);
      }
    };

    eventSource.onerror = (err) => {
      console.error("❌ SSE 连接错误:", err);
      try {
        eventSource.close();
      } catch {}
      const endEvent = new Event("end");
      eventSource.dispatchEvent(endEvent);
    };

    return eventSource;
  },
};

export default FundamentalAgentAPI;

